<template>
  <view class="container">
    <view class="form">
      <view class="form-group">
        <text class="label">所在城市</text>
        <picker :value="formData.cityIndex" :range="cityOptions" range-key="name" @change="onCityChange">
          <view class="picker-view">{{ formData.city || '请选择城市' }}</view>
        </picker>
      </view>

      <view class="form-group">
        <text class="label">小区/大厦/学校</text>
        <input class="input" v-model="formData.department" placeholder="请输入详细地址" />
      </view>

      <view class="form-group">
        <text class="label">楼号-门牌号</text>
        <input class="input" v-model="formData.houseNumber" placeholder="例如: 2号楼10号" />
      </view>

      <view class="form-group">
        <text class="label">收货人</text>
        <input class="input" v-model="formData.name" placeholder="请输入收货人姓名" />
      </view>

      <view class="form-group">
        <text class="label">联系电话</text>
        <input class="input" v-model="formData.phone" placeholder="请输入联系电话" />
      </view>

      <button class="submit-btn" @click="submitForm">保存</button>
    </view>
  </view>
</template>

<script>
<<<<<<< HEAD
	import config from '../../config';
=======
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
export default {
  data() {
    return {
      formData: {
        _id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        cityIndex: -1 // 用于保存选中的城市索引
      },
      cityOptions: [
        { name: '北京市' },
        { name: '上海市' },
        { name: '广州市' },
        { name: '深圳市' },
        { name: '成都市' }
      ]
    }
  },
  onLoad(options) {
    if (options.id) {
      this.fetchAddressDetail(options.id);
    }
  },
  methods: {
    // 获取地址详情
    async fetchAddressDetail(id) {
      try {
        uni.showLoading({ title: '加载中...' });
        const response = await uni.request({
<<<<<<< HEAD
          url: config.URL+`/address?id=${id}`,
=======
          url: `https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address?id=${id}`,
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
          method: 'GET'
        });

        // 处理响应对象，直接访问statusCode和data
        if (response.statusCode === 200) {
          const data = response.data[0]; // 假设返回的是一个数组
          this.formData = {
            _id: data._id || data.id,
            city: data.city || '',
            department: data.department || '',
            houseNumber: data.houseNumber || '',
            name: data.name || '',
            phone: data.phone || ''
          };
          // 设置城市索引
          this.formData.cityIndex = this.cityOptions.findIndex(option => option.name === this.formData.city);
        } else {
          throw new Error('获取地址详情失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '获取地址详情失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 提交表单
    async submitForm() {
      if (!this.validateForm()) return;

      uni.showLoading({ title: '保存中...' });
      try {
<<<<<<< HEAD
        let url = config.URL+'/address';
=======
        let url = 'https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address';
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
        let method = 'POST';
        
        if (this.formData._id) {
          // 如果有_id，则为更新操作
          url += `/${this.formData._id}`;
          method = 'PUT';
        }

        const submitData = { ...this.formData };

        const response = await uni.request({
          url,
          method,
          data: submitData,
          header: {
            'Content-Type': 'application/json'
          }
        });

        if (response.statusCode === 200 || response.statusCode === 201) {
          uni.showToast({ title: '保存成功', icon: 'success' });
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/address/index' });
          }, 1500);
        } else {
          throw new Error(response.data.message || '保存失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 表单验证（保持不变）
    validateForm() {
      if (!this.formData.city) {
        uni.showToast({
          title: '请选择城市',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.department) {
        uni.showToast({
          title: '请填写详细地址',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.houseNumber) {
        uni.showToast({
          title: '请填写门牌号',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.name) {
        uni.showToast({
          title: '请填写收货人姓名',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.phone || !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        });
        return false;
      }

      return true;
    },
    
    // 处理城市选择变化
    onCityChange(event) {
      this.formData.cityIndex = event.target.value;
      this.formData.city = this.cityOptions[this.formData.cityIndex].name;
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
body {
  font-family: 'Open Sans', sans-serif;
  margin: 0;
  padding: 0;
  background-color: #eaf2f8;
}

.container {
  padding: 20px;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  width: 450px;
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-group {
  margin-bottom: 30px;
}

.label {
  display: block;
  margin-bottom: 12px;
  color: #444;
  font-size: 18px;
  font-weight: 500;
}

.input {
  width: 100%;
  height: 55px;
  border: 1px solid #d3e1ec;
  border-radius: 8px;
  padding: 0 18px;
  box-sizing: border-box;
  font-size: 16px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  color: #333;
}

.input::placeholder {
  color: #999;
}

.input:focus {
  border-color: #00a2ff;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 162, 255, 0.2);
}

.submit-btn {
  background-color: #00a2ff;
  color: white;
  border: none;
  height: 55px;
  border-radius: 8px;
  margin-top: 20px;
  font-size: 18px;
  font-weight: 500;
  width: 100%;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background-color: #0087e6;
}

.picker-view {
  width: 100%;
  height: 55px;
  border: 1px solid #d3e1ec;
  border-radius: 8px;
  padding: 0 18px;
  box-sizing: border-box;
  font-size: 16px;
  line-height: 55px;
  color: #333;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.picker-view:focus {
  border-color: #00a2ff;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 162, 255, 0.2);
}

.picker {
  width: 100%;
  height: 55px;
}
</style>
